package com.bhs.sansonglogistics.ui.enterprise;

import static com.bhs.sansonglogistics.base.MyApplication.getContext;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.GlideEngine;
import com.bhs.sansonglogistics.bean.CompanyApproveInfoBean;
import com.bhs.sansonglogistics.bean.CompanyBean;
import com.bhs.sansonglogistics.bean.ImageReturn;
import com.bhs.sansonglogistics.dialog.BottomSelectDialog;
import com.bhs.sansonglogistics.dialog.CityPickerDialog;
import com.bhs.sansonglogistics.dialog.MyClickListener;
import com.bhs.sansonglogistics.dialog.MyClickListener2;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.home.MainActivity;
import com.bhs.sansonglogistics.ui.home.SourceGoodsListFragment;
import com.bhs.sansonglogistics.ui.mine.PersonalInformationActivity;
import com.bhs.sansonglogistics.ui.order.PreemptActivity;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Address;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 企业认证
 */
public class EnterpriseCertificationActivity extends BaseActivity implements View.OnClickListener, NetCallBack, TextWatcher, EasyPermissions.PermissionCallbacks {

    private RelativeLayout rlTitle;
    private TextView tvSkip;
    private LinearLayout llBusinessLicense;
    private EditText etCorporateName;
    private EditText etPersonCharge;
    private EditText etTelephone;
    private TextView etAddress;
    private TextView tvCity;
    private Button btnSubmit;
    private RelativeLayout mLlBg;
    private EditText mEtBusinessLicenseNumber;
    private EditText mEtLegalPerson;
    private String businessLicense;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private String province;
    private String city;
    private String county;
    String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE};
    double latitude, longitude;
    private ImageView mIvBusinessLicense;
    private ImageView mIvAuthenticationStatus;
    private ScrollView mSvInfo;
    private TextView mTvHint;
    private int type;
    private String CityLocation;

    @Override
    public int initLayout() {
        return R.layout.activity_enterprise_certification;
    }

    @Override
    public void initView() {
        type = getIntent().getIntExtra("type", 0);
        rlTitle = findViewById(R.id.rl_title);
        tvSkip = findViewById(R.id.tv_skip);
        llBusinessLicense = findViewById(R.id.ll_business_license);
        llBusinessLicense.setOnClickListener(this);
        etCorporateName = findViewById(R.id.et_corporate_name);
        etPersonCharge = findViewById(R.id.et_person_charge);
        etTelephone = findViewById(R.id.et_telephone);
        etAddress = findViewById(R.id.et_address);
        etAddress.setOnClickListener(this);
        tvCity = findViewById(R.id.tv_city);
        btnSubmit = findViewById(R.id.btn_submit);
        btnSubmit.setOnClickListener(this);
        mLlBg = findViewById(R.id.ll_bg);
        tvCity.setOnClickListener(this);
        mLlBg.setOnClickListener(this);
        mEtBusinessLicenseNumber = findViewById(R.id.et_business_license_number);
        mEtLegalPerson = findViewById(R.id.et_legal_person);
        etTelephone.addTextChangedListener(this);
        etPersonCharge.addTextChangedListener(this);
        etAddress.addTextChangedListener(this);
        etCorporateName.addTextChangedListener(this);
        mEtBusinessLicenseNumber.addTextChangedListener(this);
        mEtLegalPerson.addTextChangedListener(this);
        tvSkip.setOnClickListener(this);
        findViewById(R.id.fl_location).setOnClickListener(this);
        mIvBusinessLicense = findViewById(R.id.iv_business_license);
        mIvAuthenticationStatus = findViewById(R.id.iv_authentication_status);
        mSvInfo = findViewById(R.id.sv_info);
        mTvHint = findViewById(R.id.tv_hint);
    }

    @Override
    public void initData() {
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {

                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    etAddress.setText(result.getData().getStringExtra("address"));
                    longitude = result.getData().getDoubleExtra("longitude", 0);
                    latitude = result.getData().getDoubleExtra("latitude", 0);
                    CityLocation = result.getData().getStringExtra("city");
                    province = result.getData().getStringExtra("province");
                    city = result.getData().getStringExtra("city");
                    county = result.getData().getStringExtra("county");
                    tvCity.setText(city);
                    verify();
                }
            }
        });
        networkRequest(netApi.getCompanyApproveInfo(), this, 9526);

    }

    private BasePopupView basePopupView;
    private BottomSelectDialog bottomSelectDialog;

    @Override
    public void onClick(View v) {
        if (btnSubmit.getText().toString().equals("认证成功")) {
            return;
        }
        int id = v.getId();
        switch (id) {
            case R.id.ll_business_license:
            case R.id.ll_bg:
                bottomSelect();
                break;
            case R.id.btn_submit:
                if (btnSubmit.getText().toString().equals("提交认证")) {
                    submit();
                } else if (btnSubmit.getText().toString().equals("返回")) {
                    finish();
                } else if (btnSubmit.getText().toString().equals("重新认证")) {
                    mSvInfo.setVisibility(View.VISIBLE);
                    mIvAuthenticationStatus.setVisibility(View.GONE);
                    mTvHint.setVisibility(View.GONE);
                    btnSubmit.setText("提交认证");
                }
                break;
            case R.id.tv_city:
                //自动获取
                 bottomSelectCity();
                break;
            case R.id.tv_skip:

                break;
            case R.id.fl_location:
            case R.id.et_address:
                methodRequiresTwoPermission();
                break;
        }
    }


    CityPickerDialog cityPickerDialog;

    private void bottomSelectCity() {
        if (cityPickerDialog == null) {
            cityPickerDialog = new CityPickerDialog(this, false);
            cityPickerDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    String[] address = info.split(",");
                    province = address[0];
                    city = address[1];
                    county = address[2];
                    tvCity.setText(city);
                    verify();
                }
            });
        }

        cityPickerDialog.show();
        cityPickerDialog.cityPickerReuse.setCity(CityLocation);
    }

    private void submit() {
        if (etCorporateName.getTag() == null) {
            ToastUtil.show("未获取正常的营业执照，请重新上传照片");
            return;
        }
        Map<String, String> parameters = new ArrayMap<>();
        parameters.put("license_pic", businessLicense);
        parameters.put("company_name", etCorporateName.getText().toString());
        parameters.put("license_no", etCorporateName.getTag() != null ? (String) etCorporateName.getTag() : "");
        parameters.put("legal_truename", mEtLegalPerson.getText().toString());
        parameters.put("contact", etPersonCharge.getText().toString());
        parameters.put("mobile", etTelephone.getText().toString());
        parameters.put("address", etAddress.getText().toString());
        parameters.put("province", province);
        parameters.put("city", city);
        parameters.put("county", county);
        parameters.put("latitude", String.valueOf(latitude));
        parameters.put("longitude", String.valueOf(longitude));
        networkRequest(netApi.applyCompanyApproval(parameters), this);
        networkRequest(netApi.update_user_info("city", city), this);
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(businessLicense)) {
            verify = false;
        }
        if (TextUtils.isEmpty(etCorporateName.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(etPersonCharge.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(etTelephone.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(etAddress.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(tvCity.getText())) {
            verify = false;
        }

        btnSubmit.setEnabled(verify);
        btnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    private void bottomSelect() {
        if (basePopupView == null) {
            bottomSelectDialog = new BottomSelectDialog(this);
            bottomSelectDialog.setMyClickListener(new MyClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.tv_take_picture) {
                        photograph();
                    } else if (v.getId() == R.id.tv_photo_album) {
                        photoAlbum();
                    }
                    basePopupView.dismiss();
                }
            });
            basePopupView = new XPopup.Builder(EnterpriseCertificationActivity.this)
                    .asCustom(bottomSelectDialog)
                    .show();
        } else {
            basePopupView.show();
        }
    }

    private void photograph() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        MyUtils.imageUpload(EnterpriseCertificationActivity.this, result, EnterpriseCertificationActivity.this, 9527);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private void photoAlbum() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(1)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        MyUtils.imageUpload(EnterpriseCertificationActivity.this, result, EnterpriseCertificationActivity.this, 9527);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {

        //上传照片
        if (requestCode == 9527) {
            ImageReturn dataBean = new Gson().fromJson(json, ImageReturn.class);
            if (dataBean.isStatus()) {
                llBusinessLicense.setVisibility(View.GONE);
                businessLicense = dataBean.getData().getSrc();
                networkRequest(netApi.identifyBusinessLicense(businessLicense), EnterpriseCertificationActivity.this, 9528);
                verify();
                Glide.with(mContext).load(dataBean.getData().getSrc()).into(mIvBusinessLicense);
            } else {
                loadingPopupDismiss();
                ToastUtil.show(dataBean.getMsg());
            }

        } else if (requestCode == 9526) {
            CompanyApproveInfoBean companyApproveInfoBean = new Gson().fromJson(json, CompanyApproveInfoBean.class);
            if (companyApproveInfoBean.isStatus()) {
                CompanyApproveInfoBean.DataDTO.CompanyApproveInfoDTO info = companyApproveInfoBean.getData().getCompany_approve_info();
                setData(info);
                if (info.getStatus() == 2) {
                    //审核失败
                    mSvInfo.setVisibility(View.GONE);
                    btnSubmit.setEnabled(true);
                    btnSubmit.setText("重新认证");
                    btnSubmit.setBackgroundColor(Color.parseColor("#485EF4"));
                    mIvAuthenticationStatus.setImageResource(R.mipmap.ic_preempt_fail);
                    mIvAuthenticationStatus.setVisibility(View.VISIBLE);
                    mTvHint.setVisibility(View.VISIBLE);
                    mTvHint.setText("认证失败");
                } else if (info.getStatus() == 0) {
                    //正在审核
                    mSvInfo.setVisibility(View.GONE);
                    btnSubmit.setEnabled(true);
                    btnSubmit.setText("返回");
                    btnSubmit.setBackgroundColor(Color.parseColor("#485EF4"));
                    mIvAuthenticationStatus.setVisibility(View.VISIBLE);
                    mTvHint.setVisibility(View.VISIBLE);
                    mTvHint.setText("审核认证中");
                } else if (info.getStatus() == 1) {
                    btnSubmit.setText("认证成功");
                    etCorporateName.setEnabled(false);
                    etPersonCharge.setEnabled(false);
                    etTelephone.setEnabled(false);
                }
            }
        } else if (requestCode == 9528) {
            //图片识别
            loadingPopupDismiss();
            CompanyBean dataBean = new Gson().fromJson(json, CompanyBean.class);
            if (dataBean.isStatus()) {
                etCorporateName.setTag(dataBean.getData().getLicense_info().getLicense_no());
                etCorporateName.setText(dataBean.getData().getLicense_info().getCompany_name());
                etPersonCharge.setText(dataBean.getData().getLicense_info().getLegal_truename());
                etAddress.setText(dataBean.getData().getLicense_info().getAddress());
                getLatlon(dataBean.getData().getLicense_info().getAddress());
            } else {
                ToastUtil.show("图片识别失败，请重新上传");
            }

        } else {
            BaseBean dataBean = new Gson().fromJson(json, BaseBean.class);
            new XPopup.Builder(this)
                    .dismissOnTouchOutside(false)
                    .dismissOnBackPressed(false)
                    .asConfirm("提示", dataBean.getMsg(),
                            null, "确定",
                            new OnConfirmListener() {
                                @Override
                                public void onConfirm() {
                                    if (dataBean.isStatus()) {
                                        if (type > 0) {
                                            finish();
                                        } else {
                                            startActivity(new Intent(EnterpriseCertificationActivity.this, MainActivity.class));
                                        }
                                    }
                                }
                            }, null, true)
                    .show();
        }

    }

    private void setData(CompanyApproveInfoBean.DataDTO.CompanyApproveInfoDTO info) {
        businessLicense = info.getLicense_pic();
        Glide.with(mContext).load(info.getLicense_pic()).into(mIvBusinessLicense);
        etCorporateName.setText(info.getCompany_name());
        etCorporateName.setTag(info.getLicense_no());
        etPersonCharge.setText(info.getContact());
        etTelephone.setText(info.getMobile());
        etAddress.setText(info.getAddress());
        tvCity.setText(info.getCity());
        province = info.getProvince();
        city = info.getCity();
        county = info.getCounty();
        latitude = info.getLatitude();
        longitude = info.getLongitude();
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {

        }

    }

    public static final int RC_LOCATION = 1; // requestCode

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            goPage();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我需要您的位置信息来获取当前地址",
                    RC_LOCATION, perms);
        }
    }

    //当申请的权限里有一个或多个被允许时
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    //当申请的权限里有一个或多个被拒绝时或者有的权限之前已被拒绝且用户选择"不再提示"时
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("提示").setRationale("此功能需要开通权限，请转到设置打开位置和电话状态权限").build().show();
        }

    }

    public void goPage() {
        Intent intent = new Intent(EnterpriseCertificationActivity.this, LocationSelectionActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    private void getLatlon(String cityName) {

        GeocodeSearch geocodeSearch = null;
        try {
            geocodeSearch = new GeocodeSearch(this);
        } catch (AMapException e) {
            throw new RuntimeException(e);
        }
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

                if (i == 1000) {
                    if (geocodeResult != null && geocodeResult.getGeocodeAddressList() != null &&
                            geocodeResult.getGeocodeAddressList().size() > 0) {
                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                        longitude = geocodeAddress.getLatLonPoint().getLongitude();
                        latitude = geocodeAddress.getLatLonPoint().getLatitude();
                        CityLocation = geocodeAddress.getCity();
                        tvCity.setText(geocodeAddress.getCity());
                        province = geocodeAddress.getProvince();
                        city = geocodeAddress.getCity();
                        county = geocodeAddress.getCountry();
                    } else {
                        Toast.makeText(EnterpriseCertificationActivity.this, "地名出错", Toast.LENGTH_SHORT).show();
//                        ToastUtils.show(context,"地址名出错");
                    }
                }
            }
        });

        GeocodeQuery geocodeQuery = new GeocodeQuery(cityName.trim(), "29");
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);

    }
}